package com.free.utils.crypt;

import com.free.exception.SystemRuntimeException;
import com.free.utils.CharsetUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SimpleDESCrypt
{
    private static final String KEY_ALGORITHM = "DES";

    public static String decrypt(String encryptedBase64String, String key)
    {
        if (StringUtils.isEmpty(encryptedBase64String))
        {
            return "";
        }
        
        byte[] decodedContent = Base64.decodeBase64(encryptedBase64String);

        try
        {
            SecretKey secretKey = createKey(key);

            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            byte[] b = cipher.doFinal(decodedContent);
            return new String(b, CharsetUtils.UTF8);
        }
        catch (UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException
                | NoSuchAlgorithmException | NoSuchPaddingException e)
        {
            throw new SystemRuntimeException("解密出错", e);
        }
    }

    private static SecretKey createKey(String key) throws UnsupportedEncodingException
    {
        byte keyByte[] = key.getBytes(CharsetUtils.UTF8);
        return new SecretKeySpec(keyByte, KEY_ALGORITHM);
    }

    // TEST
    public static void main(String[] args)
    {
        String mingwen = SimpleDESCrypt.decrypt("4SLxRkXc41xKU7Mlb5M1sg==", "MyNJ922J");
        System.out.println(mingwen);
    }

}
